package com.polaris.live.common.network.interceptor

import android.text.TextUtils
import com.blankj.utilcode.util.EncryptUtils
import com.hjq.language.MultiLanguages
import com.polaris.live.common.AppModule
import com.polaris.live.common.appContext
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.ServerConfig
import com.polaris.live.common.network.EncryptHelper
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okio.Buffer

/**
 * CommonParamsInterceptor 头部拦截器
 *
 * @author Created by 半仙 on 2023/7/31/031 16:37
 */
class CommonParamsInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val builder = request.newBuilder()

        val timesTamp = CacheUtil.getServerTime()
        val locale = MultiLanguages.getSystemLanguage(appContext).language
        val string = setSign(request, timesTamp, locale)//设置签名

        val newRequestBody = encrypt(request)

        builder
            .method(request.method, newRequestBody)
            .addHeader("sign", EncryptUtils.encryptSHA256ToString(string).lowercase())
            .addHeader("locale", locale)
            .addHeader("app-language", AppModule.getLanguageAndArea())
            .addHeader("timestamp", timesTamp.toString())
            .addHeader("app-type", AppConst.APP_TYPE.toString())
            .addHeader("platform-type", AppConst.PLATFORM_TYPE.toString())
            .addHeader("variant-type", AppConst.VARIANT_TYPE.toString())
            .addHeader("build-version", AppModule.getAppVersion().toString())

        val token = UserManager.getUser().token
        if (token != null) {
            builder.addHeader("token", token)
        }

        return chain.proceed(builder.build())
    }

    //请求体加密
    private fun encrypt(chain: Request): RequestBody? {
        val requestBody = chain.body
        if (requestBody != null) {
            val buffer = Buffer()
            requestBody.writeTo(buffer)
            val requestBodyString = buffer.readUtf8()

            val replace = requestBodyString.replace("\n", "")

            val encrypt = EncryptHelper.encryptParams(replace)

            return encrypt.toRequestBody(requestBody.contentType())
        }
        return null
    }

    //设置签名
    private fun setSign(chain: Request, time: Long, locale: String): String {
        val method = chain.method
        val query = chain.url.query
        val requestBody = chain.body
        val string = StringBuilder()
        if (method == "GET" || method == "DELETE") {
            if (!TextUtils.isEmpty(query)) {
                string.append("", query)
            } else {
                string.append("")
            }
        } else {
            if (requestBody != null) {
                val buffer = Buffer()
                requestBody.writeTo(buffer)
                val requestBodyString: String = buffer.readUtf8()
                if (!TextUtils.isEmpty(requestBodyString)) {
                    string.append("", requestBodyString)

                } else {
                    string.append("")
                }
            } else {
                string.append("")
            }
        }

        string.append("&locale=", locale)
            .append("&timestamp=", time.toString())
            .append(ServerConfig.getServerMode().encrypt)

        return string.toString()
    }
}